package com.mvc.base.service;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Service;

import com.mvc.base.model.Company;
import com.mvc.framework.dao.HibernateWebUtils;
import com.mvc.framework.model.Auditable;
import com.mvc.framework.service.BaseService;
import com.mvc.framework.util.FrameworkContextUtils;
import com.mvc.framework.util.PageSearch;

/**
 * 
 * @author snowpbx
 * @version V1.0 Create Time: 2012-10-5
 */
@Service
public class CompanyManager extends BaseService<Company, Integer> {

	public List<Company> getAll() {
		Company example = new Company();
		example.setRecStatus(Auditable.REC_STATUS_VALID);
		return getHibernateTemplate().findByExample(example);
	}

	public void find(final PageSearch page) {
		final Integer userId = FrameworkContextUtils.getCurrentUserId();
		getHibernateTemplate().execute(new HibernateCallback<PageSearch>() {
			public PageSearch doInHibernate(Session session) {
				Criteria criteria = HibernateWebUtils.createCriteria(session, page.getEntityClass(), page.getFilters());
				if (userId != null && userId != FrameworkContextUtils.ADMIN_ID) {
					criteria.add(Restrictions.sqlRestriction("object_Id in (select B.company_Id from B_USER_COMPANY B"
					        + " where B.user_id = " + userId + ")"));
				}
				if (0 == page.getTotalCount()) {
					criteria.setProjection(Projections.rowCount());
					Object object = criteria.uniqueResult();
					int total = object == null ? 0 : ((Number) object).intValue();
					page.setTotalCount(total);
				}
				addOrder(page, criteria);
				criteria.setProjection(null);
				List items = criteria.setFirstResult(page.getBegin()).setMaxResults(page.getPageSize()).list();
				page.setList(items);
				return page;
			}
		});
	}
}
